/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.demister.at.util;

/**
 *
 * @author rock
 */
public class BitOperations {

    /**
     * Return the integer value of given integer at start bit and length. Bit counts from 1.
     * @param i source integer
     * @param start start bit
     * @param length bit length
     * @return
     */
    public static int getNumberOnBits(int i, int start, int length) {
        return (i >>> (start - 1)) & ((1 << length) - 1);
    }

    /**
     * Return new integer value of modifying given integer at start bit and length with new value.
     * @param i source integer
     * @param start start bit
     * @param length bit length
     * @param value new value
     * @return
     */
    public static int setNumberOnBits(int i, int start, int length, int value) {
        return (i &
               reverseBits((1 << (start + length - 1))- (1 << (start - 1)))|
               ((value & ((1 << length) - 1)) << (start - 1)));
    }

    /**
     * Return the integer value with reverse bit value of given integer.
     * @param i
     * @return
     */
    public static int reverseBits(int i) {
        return  -i - 1;
    }
}
